package com.quasar.hpatient.view;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.controllermodel.PictureConstant;
import com.quasar.hpatient.model.event.CloseEvent;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.event.UpdatePhoto;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.TestRecordData;
import com.quasar.hpatient.onInterface.viewInterface.UiInterface;
import com.quasar.hpatient.presenter.UpdateInspectionPicPresenter;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 编辑图片界面
 */
@OptionsMenu(R.menu.menu_editphoto)
@EActivity(R.layout.activity_edit_image)
public class EditImageActivity extends BaseActivity implements PictureConstant.updateUiInit, UiInterface<DataStateResult> {

    @Extra
    String imageUrls;  //传递图片
    @Extra
    int indexPath;

    @Extra
    int postion;//记录编辑的图片下表
    @Extra
    TestRecordData.PicListBean picListBean;//保存传递过来的图片对象

    @ViewById(R.id.image)
    ImageView image;

    String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
            .format(new Date());
    String fileName = "osc_" + timeStamp + ".jpg";// 照片命名
    //图片上传
    PictureConstant pictureConstant;
    UpdateInspectionPicPresenter updateInspectionPicPresenter;

    @AfterViews
    void init() {
        initToolbar();
        initView();
        initData();
    }

    @Override
    protected void initView() {
        pictureConstant = new PictureConstant(this);
        updateInspectionPicPresenter = new UpdateInspectionPicPresenter(this);

    }

    @Override
    protected void initData() {

        if (imageUrls != null) {
            Glide.with(EditImageActivity.this)
                    .load(imageUrls)
                    .asBitmap()
                    .into(image);
        }
    }

    int angle = 0;

    @OptionsItem(R.id.action_rotate)  //旋转按钮
    public void action_rotate() {
        angle = angle + 90;
        image.setRotation(angle);
        if (angle == 360) {
            angle = 0;
        }
    }

    @OptionsItem(R.id.action_save)  //保存按钮
    public void action_save() {
        try {
            Bitmap images = ((BitmapDrawable) image.getDrawable()).getBitmap();
            if (images != null) {
                Matrix matrix = new Matrix();
                matrix.postRotate(angle);
                Bitmap resizedBitmap = Bitmap.createBitmap(images, 0, 0,
                        images.getWidth(), images.getHeight(), matrix, true);
                saveppic();
                showDialog();
                savePic(resizedBitmap, path, fileName);
            }
        } catch (Exception e) {
            msg("请稍后...");
        }
    }

    public void savePic(Bitmap bitmap, String path, String filename) {

        if (path != null && !"".equals(path)) {
            File file = new File(path, filename);
            FileOutputStream out;
            try {
                out = new FileOutputStream(file);
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, 40, out)) {
                    out.flush();
                    out.close();
                }

                List<File> listFile = new ArrayList<>();
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(path);
                stringBuffer.append(fileName);

                File files = new File(stringBuffer.toString());
                if (files != null) {
                    listFile.add(files);

                    pictureConstant.PostPicture(listFile);
                }
            } catch (FileNotFoundException e) {
                pd.dismiss();
            } catch (IOException e) {
                pd.dismiss();
            }
        }
    }

    //保存上传编辑后的返回图片地址
    String backPhoto=null;
    @Override
    public void updateInit(String path) {
        //picListBean
        if (picListBean != null) {
            backPhoto=path;
            updateInspectionPicPresenter.UpdateInspectionPic(picListBean.getId() + "", path);
        }
    }

    @Override
    public void onErrPhoto(String errVal) {
        if (errVal != null) {
            msg("图片上传失败" + errVal);
        }
    }

    @Override
    public void onViewSuccess(DataStateResult data) {
        ViseLog.d("修改成功" + data.getMsgCode());
        if (data.getMsgCode().equals("0x00000000")) {
//            UpdateEvent updateEvent = new UpdateEvent();
//            updateEvent.type = ConstantManger.ClosePhoto;
//            EventBus.getDefault().post(updateEvent);
//            pd.dismiss();
//            finish();

            UpdatePhoto updatePhoto=new UpdatePhoto();
            updatePhoto.urlpath=backPhoto;
            updatePhoto.postion=postion;
            EventBus.getDefault().post(updatePhoto);
            pd.dismiss();
            finish();
        }

    }

    @Override
    public void onViewError(String msg) {
        ViseLog.d("修改失败" + msg);
        pd.dismiss();
    }

    @Override
    public void onViewRefreshUI() {

    }

    //判断文件夹是否存在不存在则创建
    public void saveppic() {
        String fenli = path;
        File fenlif = new File(fenli);
        if (!fenlif.exists()) {
            //若不存在，创建目录，可以在应用启动的时候创建
            fenlif.mkdirs();
            setTitle("paht ok,path:" + fenlif);
        }
    }


}
